document.addEventListener('DOMContentLoaded', function() {
    // 加入公司功能
    const joinCompanyStatusElem = document.getElementById('join-company-status');
    const joinCompanyFormContainer = document.getElementById('join-company-form-container');
    const submenuFeatures = document.querySelectorAll('.submenu-feature');
    
    // 检查加入公司状态
    checkJoinCompanyStatus();
    
    // 加载公告列表
    loadAnnouncements();
    
    // 初始化打卡功能
    initClockIn();
    
    // 初始化打卡记录功能
    initClockRecords();
    
    // 初始化我的任务功能
    initMyTasks();
    
    // 初始化绩点查看功能
    initPerformanceView();
    
    // 初始化调试功能
    initDebugFeatures();
    
    // 初始化个人资料功能
    initProfile();
    
    // 员工查找功能
    const searchEmployeeBtn = document.getElementById('search-employee-btn');
    const resetEmployeeSearchBtn = document.getElementById('reset-employee-search-btn');
    const employeeSearch = document.getElementById('employee-search');
    
    if (searchEmployeeBtn) {
        searchEmployeeBtn.addEventListener('click', function() {
            const keyword = employeeSearch.value.trim();
            loadEmployees(keyword);
        });
    }
    
    if (resetEmployeeSearchBtn) {
        resetEmployeeSearchBtn.addEventListener('click', function() {
            employeeSearch.value = '';
            loadEmployees();
        });
    }
    
    if (employeeSearch) {
        employeeSearch.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const keyword = employeeSearch.value.trim();
                loadEmployees(keyword);
            }
        });
    }
    
    // 初始化员工模态框
    initEmployeeModal();
    
    // 检查当前页面，如果是员工页面则加载员工列表
    const activeMenu = document.querySelector('.submenu-item a.active');
    if (activeMenu && activeMenu.getAttribute('data-target') === 'employees') {
        loadEmployees();
    }
    
    // 绑定刷新状态按钮事件
    const refreshJoinStatusBtn = document.getElementById('refresh-join-status-btn');
    if (refreshJoinStatusBtn) {
        refreshJoinStatusBtn.addEventListener('click', function() {
            // 添加旋转动画
            const icon = this.querySelector('i');
            icon.classList.add('fa-spin');
            
            // 刷新加入公司状态
            checkJoinCompanyStatus();
            
            // 显示刷新成功提示
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.textContent = '状态已刷新';
            document.body.appendChild(toast);
            
            // 2秒后移除提示和旋转动画
            setTimeout(function() {
                toast.remove();
                icon.classList.remove('fa-spin');
            }, 2000);
        });
    }
    
    // 绑定刷新公告按钮事件
    const refreshAnnouncementsBtn = document.getElementById('refresh-announcements-btn');
    if (refreshAnnouncementsBtn) {
        refreshAnnouncementsBtn.addEventListener('click', function() {
            // 添加旋转动画
            const icon = this.querySelector('i');
            icon.classList.add('fa-spin');
            
            // 刷新公告列表
            loadAnnouncements();
            
            // 显示刷新成功提示
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.textContent = '公告已刷新';
            document.body.appendChild(toast);
            
            // 2秒后移除提示和旋转动画
            setTimeout(function() {
                toast.remove();
                icon.classList.remove('fa-spin');
            }, 2000);
        });
    }
    
    // 绑定刷新打卡状态按钮事件
    const refreshAttendanceBtn = document.getElementById('refresh-attendance-btn');
    if (refreshAttendanceBtn) {
        refreshAttendanceBtn.addEventListener('click', function() {
            // 添加旋转动画
            const icon = this.querySelector('i');
            icon.classList.add('fa-spin');
            
            // 强制刷新打卡状态
            forceRefreshAttendanceStatus();
            
            // 显示刷新成功提示
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.textContent = '打卡状态已刷新';
            document.body.appendChild(toast);
            
            // 2秒后移除提示和旋转动画
            setTimeout(function() {
                toast.remove();
                icon.classList.remove('fa-spin');
            }, 2000);
        });
    }
    
    // 绑定打卡按钮事件
    const checkInBtn = document.getElementById('check-in-btn');
    if (checkInBtn) {
        checkInBtn.addEventListener('click', function() {
            checkIn();
        });
    }
    
    // 绑定下班打卡按钮事件
    const checkOutBtn = document.getElementById('check-out-btn');
    if (checkOutBtn) {
        checkOutBtn.addEventListener('click', function() {
            checkOut();
        });
    }
    
    // 绑定刷新打卡记录按钮事件
    const refreshRecordsBtn = document.getElementById('refresh-records-btn');
    if (refreshRecordsBtn) {
        refreshRecordsBtn.addEventListener('click', function() {
            const date = document.getElementById('user-record-date').value;
            loadAttendanceRecords(date);
        });
    }
    
    // 扩展home.js中的菜单点击事件处理，添加特定功能的初始化
    const menuItems = document.querySelectorAll('.submenu-item a');
    menuItems.forEach(item => {
        const originalClickHandler = item.onclick;
        
        item.addEventListener('click', function() {
            const target = this.getAttribute('data-target');
            
            // 根据目标执行相应的初始化
            if (target === 'employees') {
                loadEmployees();
            } else if (target === 'clock-in') {
                loadTodayAttendanceRecord();
            } else if (target === 'clock-records') {
                loadAttendanceRecords();
            } else if (target === 'performance-points') {
                loadUserPerformance();
            }
        });
    });
    
    // 只显示时间部分的工具函数
    window.formatTimeOnly = function(dateTimeStr) {
        if (!dateTimeStr) return '';
        
        try {
            // 首先尝试将日期时间字符串分割，获取时间部分
            const parts = dateTimeStr.split(' ');
            if (parts.length > 1) {
                return parts[1];
            }
            
            // 如果不能分割，尝试创建Date对象并格式化
            const date = new Date(dateTimeStr);
            if (!isNaN(date.getTime())) {
                // 格式化为 HH:MM:SS
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                const seconds = date.getSeconds().toString().padStart(2, '0');
                return `${hours}:${minutes}:${seconds}`;
            }
            
            // 如果都失败，返回原始字符串
            // console.warn('无法解析时间格式:', dateTimeStr);
            return dateTimeStr;
        } catch (e) {
            // console.error('时间格式化错误:', e);
            return dateTimeStr;
        }
    };
    
    function checkJoinCompanyStatus() {
        fetch('checkJoinCompanyStatus')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.inCompany) {
                    // 用户已加入公司，启用所有功能
                    enableFeatures();
                    
                    // 检查是否有离职申请
                    fetch('checkResignationStatus')
                        .then(response => response.json())
                        .then(resignData => {
                            if (resignData.success && resignData.status === 3) {
                                // 有待审核的离职申请
                                const application = data.application || {};
                                
                                // 合并离职申请信息
                                if (resignData.resignation) {
                                    application.status = 3; // 设置状态为离职申请中
                                    application.resignationReason = resignData.resignation.resignationReason;
                                    application.resignationTime = resignData.resignation.resignationTime;
                                }
                                
                                displayApplicationStatus(application);
                            } else {
                                // 显示已加入公司的状态
                                displayCompanyInfo(data.application);
                            }
                        })
                        .catch(error => {
                            // console.error('检查离职状态出错:', error);
                            // 出错时仍显示公司信息
                            displayCompanyInfo(data.application);
                        });
                } else if (data.application) {
                    // 用户有申请记录但不在公司
                    disableFeatures();
                    displayApplicationStatus(data.application);
                } else {
                    // 用户不在公司，也没有申请记录，显示申请表单
                    disableFeatures();
                    displayJoinCompanyForm();
                }
            } else {
                joinCompanyStatusElem.innerHTML = `
                    <div class="alert alert-danger">
                        ${data.message || '获取加入公司状态失败，请刷新页面重试'}
                    </div>
                `;
            }
        })
        .catch(error => {
            // console.error('获取加入公司状态出错:', error);
            joinCompanyStatusElem.innerHTML = `
                <div class="alert alert-danger">
                    系统错误，请刷新页面重试
                </div>
            `;
        });
    }
    
    function displayCompanyInfo(application) {
        if (!application) {
            joinCompanyStatusElem.innerHTML = `
                <div class="status-box status-approved">
                    您已成功加入公司
                </div>
            `;
            joinCompanyFormContainer.innerHTML = `
                <div class="alert alert-info">
                    您已成功加入公司，可以使用所有功能。
                </div>
            `;
            return;
        }
        
        joinCompanyStatusElem.innerHTML = `
            <div class="status-box status-approved">
                您已成功加入 ${application.companyName}
            </div>
        `;
        
        joinCompanyFormContainer.innerHTML = `
            <div class="company-info">
                <p><strong>公司名称：</strong>${application.companyName}</p>
                <p><strong>员工编号：</strong>${application.employeeNumber}</p>
                <p><strong>职位：</strong>${application.position || '未设置'}</p>
                <p><strong>基础薪资：</strong>${application.baseSalary ? application.baseSalary + ' 元' : '未设置'}</p>
                <p><strong>申请时间：</strong>${formatDateTime(application.createTime)}</p>
                <p><strong>通过时间：</strong>${formatDateTime(application.updateTime)}</p>
            </div>
        `;
    }
    
    function displayApplicationStatus(application) {
        let statusClass, statusText;
        
        switch(application.status) {
            case 0:
                statusClass = 'status-pending';
                statusText = '审核中';
                break;
            case 1:
                statusClass = 'status-approved';
                statusText = '已通过';
                break;
            case 2:
                statusClass = 'status-rejected';
                statusText = '已拒绝';
                break;
            case 3:
                statusClass = 'status-pending';
                statusText = '待审核离职';
                break;
            default:
                statusClass = 'status-none';
                statusText = '未知状态';
        }
        
        joinCompanyStatusElem.innerHTML = `
            <div class="status-box ${statusClass}">
                加入公司申请状态：${statusText}
            </div>
        `;
        
        let content = `
            <div class="application-info">
                <p><strong>申请公司：</strong>${application.companyName}</p>
                <p><strong>申请原因：</strong>${application.reason || '无'}</p>
                <p><strong>申请时间：</strong>${formatDateTime(application.createTime)}</p>
        `;
        
        if (application.status === 0) {
            // 申请审核中
            content += `
                <div class="alert alert-warning">
                    您的申请正在审核中，请耐心等待。
                </div>
            `;
            // 确保功能被禁用
            disableFeatures();
        } else if (application.status === 1) {
            // 申请已通过
            content += `
                <p><strong>员工编号：</strong>${application.employeeNumber}</p>
                <p><strong>职位：</strong>${application.position || '未设置'}</p>
                <p><strong>基础薪资：</strong>${application.baseSalary ? application.baseSalary + ' 元' : '未设置'}</p>
                <p><strong>通过时间：</strong>${formatDateTime(application.updateTime)}</p>
                <div class="alert alert-success">
                    恭喜！您的申请已通过，现在可以使用所有功能。
                </div>
            `;
            // 先禁用再启用，确保事件监听器正确重置
            disableFeatures();
            enableFeatures();
        } else if (application.status === 2) {
            // 申请已拒绝
            content += `
                <p><strong>拒绝原因：</strong>${application.rejectReason || '无'}</p>
                <p><strong>拒绝时间：</strong>${formatDateTime(application.updateTime)}</p>
                <div class="alert alert-danger">
                    很遗憾，您的申请被拒绝。您可以尝试重新申请。
                </div>
                <button class="btn btn-primary" id="reapply-btn">重新申请</button>
            `;
            // 确保功能被禁用
            disableFeatures();
        } else if (application.status === 3) {
            // 离职申请待审核
            content += `
                <p><strong>员工编号：</strong>${application.employeeNumber}</p>
                <p><strong>职位：</strong>${application.position || '未设置'}</p>
                <p><strong>基础薪资：</strong>${application.baseSalary ? application.baseSalary + ' 元' : '未设置'}</p>
                <p><strong>离职原因：</strong>${application.resignationReason || '无'}</p>
                <p><strong>申请离职时间：</strong>${formatDateTime(application.resignationTime)}</p>
                <div class="alert alert-warning">
                    您的离职申请正在审核中，请耐心等待。在此期间，您仍可以继续使用系统功能。
                </div>
            `;
            // 先禁用再启用，确保事件监听器正确重置
            disableFeatures();
            enableFeatures();
        }
        
        content += '</div>';
        joinCompanyFormContainer.innerHTML = content;
        
        // 绑定重新申请按钮事件
        if (application.status === 2) {
            document.getElementById('reapply-btn').addEventListener('click', function() {
                displayJoinCompanyForm();
            });
        }
    }
    
    function displayJoinCompanyForm() {
        // 禁用功能
        disableFeatures();
        
        joinCompanyStatusElem.innerHTML = `
            <div class="status-box status-none">
                您尚未加入公司
            </div>
        `;
        
        // 直接显示输入公司ID的表单，不再获取公司列表
        joinCompanyFormContainer.innerHTML = `
            <form id="join-company-form">
                <div class="form-group">
                    <label for="companyId">公司ID</label>
                    <input type="text" class="form-control" id="companyId" placeholder="请输入公司ID" required>
                </div>
                <div class="form-group">
                    <label for="reason">申请理由</label>
                    <textarea class="form-control" id="reason" placeholder="请简要说明您加入该公司的理由..."></textarea>
                </div>
                <button type="submit" class="btn btn-primary">提交申请</button>
            </form>
        `;
        
        // 绑定表单提交事件
        document.getElementById('join-company-form').addEventListener('submit', submitJoinCompanyApplication);
    }
    
    function submitJoinCompanyApplication(event) {
        event.preventDefault();
        
        const companyId = document.getElementById('companyId').value;
        const reason = document.getElementById('reason').value;
        
        if (!companyId) {
            alert('请输入公司ID');
            return;
        }
        
        // 禁用提交按钮
        const submitBtn = event.target.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.textContent = '提交中...';
        
        // 构建表单数据
        const formData = new URLSearchParams();
        formData.append('companyId', companyId);
        formData.append('reason', reason);
        
        // 发送申请
        fetch('submitJoinCompany', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message || '申请提交成功');
                
                // 显示申请状态
                joinCompanyStatusElem.innerHTML = `
                    <div class="status-box status-pending">
                        加入公司申请状态：审核中
                    </div>
                `;
                
                // 更新表单显示
                joinCompanyFormContainer.innerHTML = `
                    <div class="application-info">
                        <p><strong>申请公司：</strong>${companyId}</p>
                        <p><strong>申请原因：</strong>${reason || '无'}</p>
                        <p><strong>申请时间：</strong>${formatDateTime(new Date())}</p>
                        <div class="alert alert-warning">
                            您的申请正在审核中，请耐心等待。
                        </div>
                    </div>
                `;
            } else {
                alert(data.message || '申请提交失败');
                // 恢复提交按钮
                submitBtn.disabled = false;
                submitBtn.textContent = '提交申请';
            }
        })
        .catch(error => {
            // console.error('提交申请出错:', error);
            alert('系统错误，请稍后再试');
            // 恢复提交按钮
            submitBtn.disabled = false;
            submitBtn.textContent = '提交申请';
        });
    }
    
    function enableFeatures() {
        submenuFeatures.forEach(item => {
            item.classList.remove('disabled');
            const link = item.querySelector('a');
            // 先移除所有可能的事件监听器
            link.removeEventListener('click', preventMenuClick);
            // 然后添加正常的点击处理
            if (!link.hasClickHandler) {
                link.addEventListener('click', handleMenuClick);
                link.hasClickHandler = true;
            }
        });
    }
    
    function disableFeatures() {
        submenuFeatures.forEach(item => {
            item.classList.add('disabled');
            const link = item.querySelector('a');
            // 移除正常的点击处理
            link.removeEventListener('click', handleMenuClick);
            // 添加阻止点击的处理
            link.addEventListener('click', preventMenuClick);
            link.hasClickHandler = false;
        });
    }
    
    function handleMenuClick(event) {
        // 正常的菜单点击处理，已在home.js中实现
    }
    
    function preventMenuClick(event) {
        event.preventDefault();
        event.stopPropagation();
        alert('您需要先加入公司才能使用此功能');
    }
    
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return '未知';
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
    }
    
    // 加载公告列表
    function loadAnnouncements() {
        const announcementsContainer = document.getElementById('announcements-container');
        if (!announcementsContainer) return;
        
        announcementsContainer.innerHTML = '<div class="loading">加载中...</div>';
        
        fetch('api/announcements')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.data && data.data.length > 0) {
                    let html = '<div class="announcement-list">';
                    data.data.forEach(announcement => {
                        const publishTime = formatDateTime(announcement.publishTime);
                        const updateTime = formatDateTime(announcement.updateTime);
                        const isUpdated = announcement.publishTime !== announcement.updateTime;
                        
                        html += `
                            <div class="announcement-item">
                                <div class="announcement-header">
                                    <h3 class="announcement-title">${announcement.title}</h3>
                                    <div class="announcement-meta">
                                        <span class="publisher">发布人: ${announcement.publisherName}</span>
                                        <span class="publish-time">发布时间: ${publishTime}</span>
                                        ${isUpdated ? `<span class="update-time">最后更新: ${updateTime}</span>` : ''}
                                    </div>
                                </div>
                                <div class="announcement-content">${announcement.content}</div>
                            </div>
                        `;
                    });
                    html += '</div>';
                    announcementsContainer.innerHTML = html;
                } else {
                    announcementsContainer.innerHTML = '<div class="alert alert-info">暂无公告</div>';
                }
            } else {
                announcementsContainer.innerHTML = `<div class="alert alert-danger">${data.message || '获取公告失败'}</div>`;
            }
        })
        .catch(error => {
            // console.error('获取公告出错:', error);
            announcementsContainer.innerHTML = '<div class="alert alert-danger">系统错误，请稍后再试</div>';
        });
    }
    
    // 加载员工列表
    function loadEmployees(keyword) {
        const employeesContainer = document.getElementById('employees-container');
        if (!employeesContainer) return;
        
        employeesContainer.innerHTML = '<div class="loading">加载中...</div>';
        
        let url = 'getEmployees';
        if (keyword) {
            url += `?keyword=${encodeURIComponent(keyword)}`;
        }
        
        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    if (data.employees && data.employees.length > 0) {
                        let html = '<div class="table-responsive"><table class="table"><thead><tr>' +
                            '<th>员工ID</th>' +
                            '<th>姓名</th>' +
                            '<th>电话</th>' +
                            '<th>职位</th>' +
                            '<th>操作</th>' +
                            '</tr></thead><tbody>';
                        
                        data.employees.forEach(employee => {
                            html += `
                                <tr>
                                    <td>${employee.id}</td>
                                    <td>${employee.userName}</td>
                                    <td>${employee.userPhone}</td>
                                    <td>${employee.position || '未设置'}</td>
                                    <td>
                                        <button class="btn btn-sm btn-info view-employee" data-id="${employee.id}">查看详情</button>
                                    </td>
                                </tr>
                            `;
                        });
                        
                        html += '</tbody></table></div>';
                        employeesContainer.innerHTML = html;
                        
                        // 绑定查看详情按钮事件
                        bindViewEmployeeButtons();
                    } else {
                        employeesContainer.innerHTML = '<div class="alert alert-info">暂无员工信息</div>';
                    }
                } else {
                    employeesContainer.innerHTML = `<div class="alert alert-danger">${data.message || '获取员工列表失败'}</div>`;
                }
            })
            .catch(error => {
                // console.error('获取员工列表出错:', error);
                employeesContainer.innerHTML = '<div class="alert alert-danger">系统错误，请稍后再试</div>';
            });
    }
    
    // 绑定查看员工详情按钮事件
    function bindViewEmployeeButtons() {
        const viewButtons = document.querySelectorAll('.view-employee');
        viewButtons.forEach(button => {
            button.addEventListener('click', function() {
                const employeeId = this.getAttribute('data-id');
                showEmployeeDetail(employeeId);
            });
        });
    }
    
    // 初始化员工详情模态框
    function initEmployeeModal() {
        const modal = document.getElementById('employee-detail-modal');
        if (!modal) return;
        
        const closeBtn = modal.querySelector('.close-modal');
        
        closeBtn.addEventListener('click', function() {
            modal.style.display = 'none';
        });
        
        window.addEventListener('click', function(event) {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        });
    }
    
    // 显示员工详情
    function showEmployeeDetail(employeeId) {
        const modal = document.getElementById('employee-detail-modal');
        const detailContent = document.getElementById('employee-detail-content');
        
        if (!modal || !detailContent) return;
        
        detailContent.innerHTML = '<div class="loading">加载中...</div>';
        modal.style.display = 'block';
        
        fetch(`getEmployeeDetail?id=${employeeId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const employee = data.employee;
                    let html = `
                        <div class="employee-detail">
                            <p><strong>员工ID：</strong>${employee.id}</p>
                            <p><strong>姓名：</strong>${employee.userName}</p>
                            <p><strong>电话：</strong>${employee.userPhone}</p>
                            <p><strong>年龄：</strong>${employee.userAge}</p>
                            <p><strong>职位：</strong>${employee.position || '未设置'}</p>
                            <p><strong>邮箱：</strong>${employee.userEmail || '未设置'}</p>
                            <p><strong>住址：</strong>${employee.userAddress || '未设置'}</p>
                        </div>
                    `;
                    detailContent.innerHTML = html;
                } else {
                    detailContent.innerHTML = `<div class="alert alert-danger">${data.message || '获取员工详情失败'}</div>`;
                }
            })
            .catch(error => {
                // console.error('获取员工详情出错:', error);
                detailContent.innerHTML = '<div class="alert alert-danger">系统错误，请稍后再试</div>';
            });
    }
});

// 初始化调试功能
function initDebugFeatures() {
    const toggleDebugBtn = document.getElementById('toggle-debug-btn');
    const debugInfo = document.getElementById('debug-info');
    
    if (toggleDebugBtn && debugInfo) {
        toggleDebugBtn.addEventListener('click', function() {
            if (debugInfo.style.display === 'none') {
                debugInfo.style.display = 'block';
            } else {
                debugInfo.style.display = 'none';
            }
        });
    }
}

// 添加调试信息
function addDebugInfo(message) {
    const debugContent = document.getElementById('debug-content');
    if (debugContent) {
        const timestamp = new Date().toLocaleTimeString();
        debugContent.textContent += `[${timestamp}] ${message}\n`;
        
        // 自动滚动到底部
        debugContent.scrollTop = debugContent.scrollHeight;
    }
}

// 强制刷新打卡状态
function forceRefreshAttendanceStatus() {
    addDebugInfo('强制刷新打卡状态');
    
    const statusContainer = document.getElementById('today-attendance-status');
    if (!statusContainer) {
        addDebugInfo('错误: 找不到打卡状态容器');
        return;
    }
    
    statusContainer.innerHTML = '<div class="loading">加载中...</div>';
    
    // 清除之前的错误消息
    const messageContainer = document.getElementById('attendance-message');
    if (messageContainer) {
        messageContainer.innerHTML = '';
    }
    
    // 强制刷新，添加时间戳参数避免缓存
    const timestamp = new Date().getTime();
    fetch(`api/attendance/checkIn?t=${timestamp}`, {
        method: 'GET',
        headers: {
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        },
        credentials: 'same-origin' // 确保发送cookies
    })
        .then(response => {
            addDebugInfo(`响应状态: ${response.status}`);
            if (!response.ok) {
                throw new Error(`网络响应不正常: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            addDebugInfo(`响应数据: ${JSON.stringify(data)}`);
            
            if (data.success) {
                // 确保按钮元素存在
                const checkInBtn = document.getElementById('check-in-btn');
                const checkOutBtn = document.getElementById('check-out-btn');
                
                if (!checkInBtn || !checkOutBtn) {
                    addDebugInfo('错误: 找不到打卡按钮');
                    return;
                }
                
                // 直接处理打卡记录
                const record = data.data;
                
                // 强制更新按钮状态
                if (record && record.checkInTime) {
                    addDebugInfo(`已上班打卡，时间: ${record.checkInTime}`);
                    
                    // 禁用上班打卡按钮
                    checkInBtn.disabled = true;
                    checkInBtn.classList.add('btn-disabled');
                    addDebugInfo('已禁用上班打卡按钮');
                    
                    // 处理下班打卡按钮
                    if (record.checkOutTime) {
                        addDebugInfo(`已下班打卡，时间: ${record.checkOutTime}`);
                        checkOutBtn.disabled = true;
                        checkOutBtn.classList.add('btn-disabled');
                        addDebugInfo('已禁用下班打卡按钮');
                    } else {
                        addDebugInfo('未下班打卡，启用下班打卡按钮');
                        checkOutBtn.disabled = false;
                        checkOutBtn.classList.remove('btn-disabled');
                        addDebugInfo('已启用下班打卡按钮');
                    }
                    
                    // 更新显示
                    updateAttendanceStatus(record);
                } else {
                    addDebugInfo('未找到上班打卡记录');
                    
                    // 启用上班打卡按钮
                    checkInBtn.disabled = false;
                    checkInBtn.classList.remove('btn-disabled');
                    addDebugInfo('已启用上班打卡按钮');
                    
                    // 禁用下班打卡按钮
                    checkOutBtn.disabled = true;
                    checkOutBtn.classList.add('btn-disabled');
                    addDebugInfo('已禁用下班打卡按钮');
                    
                    // 更新显示
                    updateAttendanceStatus(null);
                }
            } else {
                addDebugInfo(`错误: ${data.message || '获取打卡记录失败'}`);
                statusContainer.innerHTML = `<div class="error-message">${data.message || '获取打卡记录失败'}</div>`;
            }
        })
        .catch(error => {
            addDebugInfo(`错误: ${error.message}`);
            statusContainer.innerHTML = '<div class="error-message">获取今日打卡记录失败，请稍后重试</div>';
        });
}

// 在文件末尾添加打卡相关功能

// 初始化打卡功能
function initClockIn() {
    // console.log('初始化打卡功能');
    // 更新打卡页面内容
    const clockInContainer = document.getElementById('clock-in');
    if (!clockInContainer) {
        // console.error('找不到打卡容器元素');
        return;
    }
    
    // 加载今日打卡记录
    loadTodayAttendanceRecord();
}

// 加载今日打卡记录
function loadTodayAttendanceRecord() {
    // 直接调用强制刷新函数，避免代码重复
    forceRefreshAttendanceStatus();
}

// 更新打卡状态
function updateAttendanceStatus(record) {
    const statusContainer = document.getElementById('today-attendance-status');
    if (!statusContainer) {
        addDebugInfo('错误: 找不到打卡状态容器');
        return;
    }
    
    // 获取当前日期
    const today = new Date();
    const year = today.getFullYear();
    const month = (today.getMonth() + 1).toString().padStart(2, '0');
    const day = today.getDate().toString().padStart(2, '0');
    const dateStr = `${year}/${month}/${day}`;
    
    // 获取按钮元素
    const checkInBtn = document.getElementById('check-in-btn');
    const checkOutBtn = document.getElementById('check-out-btn');
    
    // 调试输出
    if (record) {
        addDebugInfo(`打卡记录数据: ${JSON.stringify(record)}`);
        if (record.checkInTime) {
            addDebugInfo(`上班打卡时间原始值: ${record.checkInTime}`);
        }
        if (record.checkOutTime) {
            addDebugInfo(`下班打卡时间原始值: ${record.checkOutTime}`);
        }
    }
    
    // 格式化打卡时间
    let checkInTimeDisplay = '未打卡';
    let checkOutTimeDisplay = '未打卡';
    
    if (record && record.checkInTime) {
        try {
            checkInTimeDisplay = formatTimeOnly(record.checkInTime);
            addDebugInfo(`格式化后的上班打卡时间: ${checkInTimeDisplay}`);
        } catch (e) {
            addDebugInfo(`上班时间格式化错误: ${e.message}`);
            checkInTimeDisplay = record.checkInTime.toString();
        }
    }
    
    if (record && record.checkOutTime) {
        try {
            checkOutTimeDisplay = formatTimeOnly(record.checkOutTime);
            addDebugInfo(`格式化后的下班打卡时间: ${checkOutTimeDisplay}`);
        } catch (e) {
            addDebugInfo(`下班时间格式化错误: ${e.message}`);
            checkOutTimeDisplay = record.checkOutTime.toString();
        }
    }
    
    // 构建HTML
    let html = `
        <h3>今日打卡状态</h3>
        <div class="attendance-date">日期：${dateStr}</div>
        <div class="attendance-time">
            <div class="check-in">
                <span>上班打卡：</span>
                <span class="time">${checkInTimeDisplay}</span>
            </div>
            <div class="check-out">
                <span>下班打卡：</span>
                <span class="time">${checkOutTimeDisplay}</span>
            </div>
        </div>
    `;
    
    statusContainer.innerHTML = html;
    
    // 更新按钮状态
    if (checkInBtn && checkOutBtn) {
        if (record && record.checkInTime) {
            // 已上班打卡
            checkInBtn.disabled = true;
            checkInBtn.classList.add('btn-disabled');
            addDebugInfo('已禁用上班打卡按钮');
            
            if (record.checkOutTime) {
                // 已下班打卡
                checkOutBtn.disabled = true;
                checkOutBtn.classList.add('btn-disabled');
                addDebugInfo('已禁用下班打卡按钮');
            } else {
                // 未下班打卡
                checkOutBtn.disabled = false;
                checkOutBtn.classList.remove('btn-disabled');
                addDebugInfo('已启用下班打卡按钮');
            }
        } else {
            // 未上班打卡
            checkInBtn.disabled = false;
            checkInBtn.classList.remove('btn-disabled');
            addDebugInfo('已启用上班打卡按钮');
            
            // 未上班打卡，不能下班打卡
            checkOutBtn.disabled = true;
            checkOutBtn.classList.add('btn-disabled');
            addDebugInfo('已禁用下班打卡按钮');
        }
    } else {
        addDebugInfo('错误: 找不到打卡按钮');
    }
}

// 格式化时间显示（仅时间部分）
function formatTimeOnly(dateObj) {
    if (!dateObj) return '未打卡';
    
    try {
        // 如果是字符串且包含GMT格式的日期时间
        if (typeof dateObj === 'string' && dateObj.includes('GMT')) {
            // 提取时间部分 HH:MM:SS
            const match = dateObj.match(/\d{2}:\d{2}:\d{2}/);
            if (match) {
                return match[0];
            }
        }
        
        // 确保是Date对象
        const date = dateObj instanceof Date ? dateObj : new Date(dateObj);
        if (isNaN(date.getTime())) {
            // console.error('无效的时间格式:', dateObj);
            return String(dateObj);
        }
        
        // 格式化为 HH:MM:SS
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        return `${hours}:${minutes}:${seconds}`;
    } catch (e) {
        // console.error('时间格式化错误:', e);
        return String(dateObj);
    }
}

// 上班打卡
function checkIn() {
    addDebugInfo('开始上班打卡');
    
    // 禁用按钮，防止重复点击
    const checkInBtn = document.getElementById('check-in-btn');
    if (checkInBtn) {
        checkInBtn.disabled = true;
        checkInBtn.innerText = '打卡完成';
    }
    
    // 清除之前的错误消息
    const messageContainer = document.getElementById('attendance-message');
    if (messageContainer) {
        messageContainer.innerHTML = '';
    }
    
    // 添加时间戳参数避免缓存
    const timestamp = new Date().getTime();
    fetch(`api/attendance/checkIn?action=checkIn&t=${timestamp}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        },
        credentials: 'same-origin' // 确保发送cookies
    })
        .then(response => {
            addDebugInfo(`上班打卡响应状态: ${response.status}`);
            if (!response.ok) {
                throw new Error(`网络响应不正常: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            addDebugInfo(`上班打卡响应数据: ${JSON.stringify(data)}`);
            
            // 显示消息
            if (messageContainer) {
                messageContainer.innerHTML = `<div class="${data.success ? 'success-message' : 'error-message'}">${data.message}</div>`;
            }
            
            if (data.success) {
                // 强制刷新打卡状态
                setTimeout(() => {
                    forceRefreshAttendanceStatus();
                }, 500);
            } else {
                // 恢复按钮状态
                if (checkInBtn) {
                    checkInBtn.disabled = false;
                    checkInBtn.innerText = '上班打卡';
                }
            }
        })
        .catch(error => {
            addDebugInfo(`上班打卡错误: ${error.message}`);
            
            // 显示错误消息
            if (messageContainer) {
                messageContainer.innerHTML = '<div class="error-message">上班打卡失败，请稍后重试</div>';
            }
            
            // 恢复按钮状态
            if (checkInBtn) {
                checkInBtn.disabled = false;
                checkInBtn.innerText = '上班打卡';
            }
        });
}

// 下班打卡
function checkOut() {
    addDebugInfo('开始下班打卡');
    
    // 禁用按钮，防止重复点击
    const checkOutBtn = document.getElementById('check-out-btn');
    if (checkOutBtn) {
        checkOutBtn.disabled = true;
        checkOutBtn.innerText = '打卡完成';
    }
    
    // 清除之前的错误消息
    const messageContainer = document.getElementById('attendance-message');
    if (messageContainer) {
        messageContainer.innerHTML = '';
    }
    
    // 添加时间戳参数避免缓存
    const timestamp = new Date().getTime();
    fetch(`api/attendance/checkIn?action=checkOut&t=${timestamp}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache, no-store, must-revalidate',
            'Pragma': 'no-cache',
            'Expires': '0'
        },
        credentials: 'same-origin' // 确保发送cookies
    })
        .then(response => {
            addDebugInfo(`下班打卡响应状态: ${response.status}`);
            if (!response.ok) {
                throw new Error(`网络响应不正常: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            addDebugInfo(`下班打卡响应数据: ${JSON.stringify(data)}`);
            
            // 显示消息
            if (messageContainer) {
                messageContainer.innerHTML = `<div class="${data.success ? 'success-message' : 'error-message'}">${data.message}</div>`;
            }
            
            if (data.success) {
                // 强制刷新打卡状态
                setTimeout(() => {
                    forceRefreshAttendanceStatus();
                }, 500);
            } else {
                // 恢复按钮状态
                if (checkOutBtn) {
                    checkOutBtn.disabled = false;
                    checkOutBtn.innerText = '下班打卡';
                }
            }
        })
        .catch(error => {
            addDebugInfo(`下班打卡错误: ${error.message}`);
            
            // 显示错误消息
            if (messageContainer) {
                messageContainer.innerHTML = '<div class="error-message">下班打卡失败，请稍后重试</div>';
            }
            
            // 恢复按钮状态
            if (checkOutBtn) {
                checkOutBtn.disabled = false;
                checkOutBtn.innerText = '下班打卡';
            }
        });
}

// 初始化打卡记录功能
function initClockRecords() {
    // 获取当前日期并格式化为YYYY-MM-DD
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    
    // 设置日期选择器默认值为今天
    const dateInput = document.getElementById('user-record-date');
    if (dateInput) {
        dateInput.value = formattedDate;
        
        // 添加日期选择器变化事件，自动筛选
        dateInput.addEventListener('change', function() {
            const date = this.value;
            loadAttendanceRecords(date);
        });
    }
    
    // 添加刷新记录按钮点击事件
    const refreshBtn = document.getElementById('refresh-records-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', function() {
            const date = document.getElementById('user-record-date').value;
            loadAttendanceRecords(date);
        });
    }
    
    // 加载打卡记录
    loadAttendanceRecords(formattedDate);
}

// 加载打卡记录
function loadAttendanceRecords(date = null) {
    const recordsContainer = document.getElementById('attendance-records-container');
    if (!recordsContainer) return;
    
    recordsContainer.innerHTML = '<div class="loading">加载中...</div>';
    
    let url = 'api/attendance/records?type=user';
    if (date) {
        url += `&date=${date}`;
    }
    
    // console.log('请求打卡记录URL:', url);
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            // console.log('获取到打卡记录数据:', data);
            if (data.success) {
                displayAttendanceRecords(data.data, date);
            } else {
                recordsContainer.innerHTML = `<div class="error-message">${data.message}</div>`;
            }
        })
        .catch(error => {
            // console.error('获取打卡记录失败:', error);
            recordsContainer.innerHTML = '<div class="error-message">获取打卡记录失败，请稍后重试</div>';
        });
}

// 显示打卡记录
function displayAttendanceRecords(records, selectedDate = null) {
    const container = document.getElementById('attendance-records-container');
    
    // console.log('显示打卡记录，记录数量:', records ? records.length : 0);
    
    if (!records || records.length === 0) {
        container.innerHTML = '<div class="no-records">暂无打卡记录</div>';
        return;
    }
    
    // 按日期分组记录
    const recordsByDate = {};
    records.forEach(record => {
        // console.log('处理记录:', record);
        
        // 提取日期部分
        let datePart = '';
        if (record.recordDate) {
            datePart = record.recordDate.split(' ')[0];
        } else if (record.attendanceDate) {
            datePart = record.attendanceDate.split(' ')[0];
        } else {
            // 如果没有日期字段，使用当前日期
            const today = new Date();
            datePart = today.toISOString().split('T')[0];
        }
        
        // console.log('记录日期:', datePart);
        
        if (!recordsByDate[datePart]) {
            recordsByDate[datePart] = [];
        }
        recordsByDate[datePart].push(record);
    });
    
    // console.log('按日期分组后的记录:', recordsByDate);
    
    let html = '';
    
    // 创建分页控件
    const dates = Object.keys(recordsByDate).sort().reverse(); // 按日期倒序排列
    const totalPages = dates.length;
    let currentPage = 1;
    
    // 如果有选定日期，找到对应的页码
    if (selectedDate) {
        const index = dates.indexOf(selectedDate);
        if (index !== -1) {
            currentPage = index + 1;
        }
    }
    
    // 创建表格
    html += `
        <table class="records-table">
            <thead>
                <tr>
                    <th>上班时间</th>
                    <th>下班时间</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody id="records-tbody">
            </tbody>
        </table>
        
        <div class="pagination" id="records-pagination">
        </div>
    `;
    
    container.innerHTML = html;
    
    // 更新分页控件
    function updatePagination() {
        const pagination = document.getElementById('records-pagination');
        let paginationHtml = '';
        
        // 上一页按钮
        paginationHtml += `<button ${currentPage === 1 ? 'disabled' : ''} id="prev-page">&laquo; 上一页</button>`;
        
        // 页码按钮 - 显示数字分页，最多显示5个页码
        const totalPageCount = dates.length;
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPageCount, startPage + 4);
        
        // 调整起始页，确保总是显示5个页码（如果总页数>=5）
        if (endPage - startPage < 4 && totalPageCount >= 5) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const pageNum = i;
            const date = dates[pageNum - 1];
            paginationHtml += `<button class="page-number ${pageNum === currentPage ? 'active' : ''}" data-page="${pageNum}" data-date="${date}">${pageNum}</button>`;
        }
        
        // 下一页按钮
        paginationHtml += `<button ${currentPage === totalPages ? 'disabled' : ''} id="next-page">下一页 &raquo;</button>`;
        
        pagination.innerHTML = paginationHtml;
        
        // 添加页码按钮事件
        document.querySelectorAll('#records-pagination button[data-page]').forEach(btn => {
            btn.addEventListener('click', function() {
                currentPage = parseInt(this.getAttribute('data-page'));
                const date = this.getAttribute('data-date');
                updateRecordsTable(date);
                updatePagination();
            });
        });
        
        // 添加上一页按钮事件
        const prevBtn = document.getElementById('prev-page');
        if (prevBtn) {
            prevBtn.addEventListener('click', function() {
                if (currentPage > 1) {
                    currentPage--;
                    const date = dates[currentPage - 1];
                    updateRecordsTable(date);
                    updatePagination();
                }
            });
        }
        
        // 添加下一页按钮事件
        const nextBtn = document.getElementById('next-page');
        if (nextBtn) {
            nextBtn.addEventListener('click', function() {
                if (currentPage < totalPages) {
                    currentPage++;
                    const date = dates[currentPage - 1];
                    updateRecordsTable(date);
                    updatePagination();
                }
            });
        }
    }
    
    // 更新表格内容
    function updateRecordsTable(date) {
        const tbody = document.getElementById('records-tbody');
        const recordsForDate = recordsByDate[date];
        
        // console.log('更新表格，日期:', date, '记录:', recordsForDate);
        
        let tableHtml = '';
        
        // 添加记录行
        recordsForDate.forEach(record => {
            // console.log('处理表格行记录:', record);
            
            // 确定打卡状态
            let statusClass = 'status-complete';
            let statusText = '正常';
            
            if (!record.checkOutTime) {
                statusClass = 'status-incomplete';
                statusText = '未下班';
            } else {
                // 检查是否迟到或早退
                if (record.isLate) {
                    statusClass = 'status-late';
                    statusText = '迟到';
                } else if (record.isEarlyLeave) {
                    statusClass = 'status-early';
                    statusText = '早退';
                }
            }
            
            tableHtml += `
                <tr>
                    <td>
                        ${record.checkInTime ? formatTimeOnly(record.checkInTime) : '未打卡'}
                        ${record.isLate ? '<span class="status-indicator late"></span>' : ''}
                    </td>
                    <td>
                        ${record.checkOutTime ? formatTimeOnly(record.checkOutTime) : '未打卡'}
                        ${record.isEarlyLeave ? '<span class="status-indicator early"></span>' : ''}
                    </td>
                    <td class="${statusClass}">${statusText}</td>
                </tr>
            `;
        });
        
        tbody.innerHTML = tableHtml;
    }
    
    // 初始化显示第一页
    if (dates.length > 0) {
        const initialDate = dates[currentPage - 1];
        updateRecordsTable(initialDate);
        updatePagination();
    } else {
        document.getElementById('records-tbody').innerHTML = '<tr><td colspan="3" class="no-records">暂无打卡记录</td></tr>';
    }
}

// 初始化我的任务功能
function initMyTasks() {
    const myTasksContent = document.getElementById('my-tasks');
    
    // 创建任务列表容器
    myTasksContent.innerHTML = `
        <h2>我的任务</h2>
        <div class="filter-container">
            <button class="filter-btn active" data-status="-1">全部</button>
            <button class="filter-btn" data-status="0">派遣中</button>
            <button class="filter-btn" data-status="1">完成待确认</button>
            <button class="filter-btn" data-status="2">已完成</button>
            <button class="refresh-btn" id="refresh-my-tasks-btn"><i class="fas fa-sync-alt"></i> 刷新</button>
        </div>
        <div id="my-task-list">
            <div class="loading">加载中...</div>
        </div>
    `;
    
    // 加载任务列表
    loadMyTasks();
    
    // 添加任务列表筛选事件
    document.querySelectorAll('#my-tasks .filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('#my-tasks .filter-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            // 切换筛选条件时，始终从第一页开始显示
            loadMyTasks(this.dataset.status, 1);
        });
    });
    
    // 添加刷新按钮事件
    document.getElementById('refresh-my-tasks-btn').addEventListener('click', function() {
        // 添加旋转动画
        const icon = this.querySelector('i');
        icon.classList.add('fa-spin');
        
        const activeFilter = document.querySelector('#my-tasks .filter-btn.active');
        const activePage = document.querySelector('#my-task-list .pagination-btn.page-btn.active');
        const currentPage = activePage ? parseInt(activePage.textContent) : 1;
        
        // 刷新当前页面的任务
        loadMyTasks(activeFilter ? activeFilter.dataset.status : -1, currentPage);
        
        // 显示刷新成功提示
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = '任务已刷新';
        document.body.appendChild(toast);
        
        // 2秒后移除提示和旋转动画
        setTimeout(function() {
            toast.remove();
            icon.classList.remove('fa-spin');
        }, 2000);
    });
}

// 加载我的任务
function loadMyTasks(status = -1, page = 1) {
    const taskList = document.getElementById('my-task-list');
    taskList.innerHTML = '<div class="loading">加载中...</div>';
    
    fetch(`./api/tasks?type=employee${status !== -1 ? '&status=' + status : ''}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.tasks && data.tasks.length > 0) {
                    // 分页逻辑
                    const pageSize = 2; // 每页显示2条记录
                    const totalTasks = data.tasks.length;
                    const totalPages = Math.ceil(totalTasks / pageSize);
                    
                    // 确保页码在有效范围内
                    const currentPage = Math.max(1, Math.min(page, totalPages));
                    
                    // 计算当前页的任务
                    const startIndex = (currentPage - 1) * pageSize;
                    const endIndex = Math.min(startIndex + pageSize, totalTasks);
                    const currentPageTasks = data.tasks.slice(startIndex, endIndex);
                    
                    // 清空任务列表并添加当前页的任务
                    taskList.innerHTML = '';
                    currentPageTasks.forEach(task => {
                        const taskItem = createMyTaskItem(task);
                        taskList.appendChild(taskItem);
                    });
                    
                    // 创建分页控件
                    const paginationContainer = document.createElement('div');
                    paginationContainer.className = 'pagination-container';
                    
                    // 添加分页信息
                    const paginationInfo = document.createElement('div');
                    paginationInfo.className = 'pagination-info';
                    paginationInfo.textContent = `第 ${currentPage}/${totalPages} 页，共 ${totalTasks} 条记录`;
                    paginationContainer.appendChild(paginationInfo);
                    
                    // 添加分页按钮
                    const paginationControls = document.createElement('div');
                    paginationControls.className = 'pagination-controls';
                    
                    // 上一页按钮
                    const prevBtn = document.createElement('button');
                    prevBtn.className = 'pagination-btn prev-btn';
                    prevBtn.textContent = '上一页';
                    prevBtn.disabled = currentPage <= 1;
                    prevBtn.addEventListener('click', function() {
                        if (currentPage > 1) {
                            const activeFilter = document.querySelector('#my-tasks .filter-btn.active');
                            const filterStatus = activeFilter ? activeFilter.dataset.status : -1;
                            loadMyTasks(filterStatus, currentPage - 1);
                        }
                    });
                    paginationControls.appendChild(prevBtn);
                    
                    // 页码按钮
                    const maxPageButtons = 5; // 最多显示5个页码按钮
                    let startPage = Math.max(1, currentPage - Math.floor(maxPageButtons / 2));
                    let endPage = Math.min(totalPages, startPage + maxPageButtons - 1);
                    
                    if (endPage - startPage + 1 < maxPageButtons) {
                        startPage = Math.max(1, endPage - maxPageButtons + 1);
                    }
                    
                    for (let i = startPage; i <= endPage; i++) {
                        const pageBtn = document.createElement('button');
                        pageBtn.className = 'pagination-btn page-btn' + (i === currentPage ? ' active' : '');
                        pageBtn.textContent = i;
                        pageBtn.addEventListener('click', function() {
                            if (i !== currentPage) {
                                const activeFilter = document.querySelector('#my-tasks .filter-btn.active');
                                const filterStatus = activeFilter ? activeFilter.dataset.status : -1;
                                loadMyTasks(filterStatus, i);
                            }
                        });
                        paginationControls.appendChild(pageBtn);
                    }
                    
                    // 下一页按钮
                    const nextBtn = document.createElement('button');
                    nextBtn.className = 'pagination-btn next-btn';
                    nextBtn.textContent = '下一页';
                    nextBtn.disabled = currentPage >= totalPages;
                    nextBtn.addEventListener('click', function() {
                        if (currentPage < totalPages) {
                            const activeFilter = document.querySelector('#my-tasks .filter-btn.active');
                            const filterStatus = activeFilter ? activeFilter.dataset.status : -1;
                            loadMyTasks(filterStatus, currentPage + 1);
                        }
                    });
                    paginationControls.appendChild(nextBtn);
                    
                    paginationContainer.appendChild(paginationControls);
                    taskList.appendChild(paginationContainer);
                } else {
                    taskList.innerHTML = '<div class="no-data">暂无任务</div>';
                }
            } else {
                taskList.innerHTML = `<div class="error-message">${data.message || '加载任务失败'}</div>`;
            }
        })
        .catch(error => {
            // console.error('Error:', error);
            taskList.innerHTML = '<div class="error-message">加载任务出错</div>';
        });
}

// 创建我的任务项
function createMyTaskItem(task) {
    const taskItem = document.createElement('div');
    taskItem.className = 'task-item';
    taskItem.dataset.id = task.id;
    
    // 根据任务状态设置不同的样式
    if (task.status === 0) {
        taskItem.classList.add('task-dispatched');
    } else if (task.status === 1) {
        taskItem.classList.add('task-completed');
    } else if (task.status === 2) {
        taskItem.classList.add('task-confirmed');
    }
    
    // 格式化日期
    const createDate = new Date(task.createTime).toLocaleString();
    let completeDate = task.completeTime ? new Date(task.completeTime).toLocaleString() : '未完成';
    let confirmDate = task.confirmTime ? new Date(task.confirmTime).toLocaleString() : '未确认';
    
    // 获取状态文本
    let statusText = '';
    if (task.status === 0) {
        statusText = '派遣中';
    } else if (task.status === 1) {
        statusText = '完成待确认';
    } else if (task.status === 2) {
        statusText = '已完成';
    }
    
    taskItem.innerHTML = `
        <div class="task-header">
            <h4 class="task-title">${task.title}</h4>
            <span class="task-status ${task.status === 0 ? 'status-dispatched' : task.status === 1 ? 'status-completed' : 'status-confirmed'}">${statusText}</span>
        </div>
        <div class="task-body">
            <p class="task-content">${task.content}</p>
            <div class="task-info">
                <p><strong>创建时间:</strong> ${createDate}</p>
                ${task.status >= 1 ? `<p><strong>完成时间:</strong> ${completeDate}</p>` : ''}
                ${task.status === 2 ? `<p><strong>确认时间:</strong> ${confirmDate}</p>` : ''}
                ${task.status === 2 ? `<p><strong>评分:</strong> <span class="task-score">${task.score}</span>/10</p>` : ''}
            </div>
        </div>
    `;
    
    // 如果任务状态为"派遣中"，添加完成按钮
    if (task.status === 0) {
        const completeBtn = document.createElement('button');
        completeBtn.className = 'btn btn-primary complete-task-btn';
        completeBtn.textContent = '完成任务';
        completeBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            completeTask(task.id);
        });
        taskItem.querySelector('.task-body').appendChild(completeBtn);
    }
    
    return taskItem;
}

// 完成任务
function completeTask(taskId) {
    if (!confirm('确定要将此任务标记为已完成吗？')) {
        return;
    }
    
    fetch('./api/task/complete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            taskId: taskId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage('任务已标记为完成，等待确认', 'success');
            
            // 获取当前筛选条件和页码
            const activeFilter = document.querySelector('#my-tasks .filter-btn.active');
            const activePage = document.querySelector('#my-task-list .pagination-btn.page-btn.active');
            const currentPage = activePage ? parseInt(activePage.textContent) : 1;
            
            // 刷新当前页面的任务
            loadMyTasks(activeFilter ? activeFilter.dataset.status : -1, currentPage);
        } else {
            showMessage('操作失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showMessage('操作出错', 'error');
    });
}

// 显示消息提示
function showMessage(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    // 2秒后自动移除提示
    setTimeout(function() {
        toast.remove();
    }, 2000);
}

// 初始化绩点查看功能
function initPerformanceView() {
    // 如果在绩点查看页面，则加载绩点数据
    const activeMenu = document.querySelector('.submenu-item a.active');
    if (activeMenu && activeMenu.getAttribute('data-target') === 'performance-points') {
        loadUserPerformance();
    }
}

// 加载用户绩点数据
function loadUserPerformance() {
    const performanceContainer = document.getElementById('performance-points');
    const contentElement = performanceContainer.querySelector('.placeholder-text');
    
    if (contentElement) {
        contentElement.innerHTML = '<div class="loading">加载中...</div>';
    }
    
    fetch('api/user/performance')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayUserPerformance(data);
            } else {
                if (contentElement) {
                    contentElement.innerHTML = `<div class="alert alert-warning">${data.message || '获取绩点数据失败'}</div>`;
                }
            }
        })
        .catch(error => {
            // console.error('获取绩点数据出错:', error);
            if (contentElement) {
                contentElement.innerHTML = '<div class="alert alert-danger">系统错误，请刷新页面重试</div>';
            }
        });
}

// 显示用户绩点数据
function displayUserPerformance(data) {
    const performanceContainer = document.getElementById('performance-points');
    
    // 如果没有记录
    if (!data.hasRecord) {
        performanceContainer.innerHTML = `
            <h2>绩点查看</h2>
            <div class="alert alert-info">暂无绩点记录</div>
        `;
        return;
    }
    
    // 获取绩点设置和记录
    const settings = data.settings;
    const performances = data.performances;
    
    // 构建HTML内容
    let html = `
        <h2>绩点查看</h2>
        <div class="performance-info">
            <div class="card">
                <div class="card-header">
                    <h3>绩点计算规则</h3>
                </div>
                <div class="card-body">
                    <p><strong>打卡时长占比:</strong> ${settings.attendancePercentage}%</p>
                    <p><strong>任务得分占比:</strong> ${settings.taskPercentage}%</p>
                    <p><strong>打卡时长满分小时数:</strong> ${settings.maxAttendanceHours}小时</p>
                    <p><strong>计算公式:</strong> 绩点 = (实际打卡时长 / ${settings.maxAttendanceHours}) × ${settings.attendancePercentage}% + (任务平均分 / 100) × ${settings.taskPercentage}%</p>
                    <p><small>注：实际打卡时长超过${settings.maxAttendanceHours}小时时，按${settings.maxAttendanceHours}小时计算</small></p>
                </div>
            </div>
        </div>
        
        <div class="performance-records">
            <h3>历史绩点记录</h3>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>年份</th>
                            <th>月份</th>
                            <th>打卡时长(小时)</th>
                            <th>任务平均分</th>
                            <th>绩点</th>
                        </tr>
                    </thead>
                    <tbody>
    `;
    
    // 按年月排序（从新到旧）
    performances.sort((a, b) => {
        if (a.year !== b.year) {
            return b.year - a.year;
        }
        return b.month - a.month;
    });
    
    // 添加每条记录
    performances.forEach(record => {
        html += `
            <tr>
                <td>${record.year}</td>
                <td>${record.month}</td>
                <td>${record.attendanceHours.toFixed(1)}</td>
                <td>${record.avgTaskScore.toFixed(1)}</td>
                <td><strong>${record.performance.toFixed(2)}</strong></td>
            </tr>
        `;
    });
    
    html += `
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    performanceContainer.innerHTML = html;
}

// 初始化个人资料功能
function initProfile() {
    // 加载个人资料
    loadUserProfile();
    
    // 修改资料按钮点击事件
    const editProfileBtn = document.getElementById('edit-profile-btn');
    if (editProfileBtn) {
        editProfileBtn.addEventListener('click', function() {
            document.getElementById('user-profile').style.display = 'none';
            document.getElementById('profile-form-container').style.display = 'block';
            this.style.display = 'none';
        });
    }
    
    // 取消修改按钮点击事件
    const cancelEditBtn = document.getElementById('cancel-edit-btn');
    if (cancelEditBtn) {
        cancelEditBtn.addEventListener('click', function() {
            document.getElementById('profile-form-container').style.display = 'none';
            document.getElementById('user-profile').style.display = 'block';
            document.getElementById('edit-profile-btn').style.display = 'inline-block';
        });
    }
    
    // 表单提交事件
    const updateProfileForm = document.getElementById('update-profile-form');
    if (updateProfileForm) {
        updateProfileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            updateUserProfile();
        });
    }
    
    // 退出公司按钮点击事件
    const leaveCompanyBtn = document.getElementById('leave-company-btn');
    if (leaveCompanyBtn) {
        leaveCompanyBtn.addEventListener('click', function() {
            if (confirm('确定要退出当前公司吗？此操作不可撤销！')) {
                leaveCompany();
            }
        });
    }
    
    // 注销账号按钮点击事件
    const deleteAccountBtn = document.getElementById('delete-account-btn');
    if (deleteAccountBtn) {
        deleteAccountBtn.addEventListener('click', function() {
            if (confirm('确定要注销账号吗？此操作不可撤销！注销后您将无法再使用此账号登录系统。')) {
                deleteAccount();
            }
        });
    }
}

// 加载用户个人资料
function loadUserProfile() {
    const userProfileElem = document.getElementById('user-profile');
    const leaveCompanyBtn = document.getElementById('leave-company-btn');
    
    fetch('getCurrentUser')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const user = data.user;
            
            // 填充表单
            document.getElementById('profile-name').value = user.name || '';
            document.getElementById('profile-gender').value = user.gender || '男';
            document.getElementById('profile-phone').value = user.phone || '';
            document.getElementById('profile-email').value = user.email || '';
            document.getElementById('profile-address').value = user.address || '';
            
            // 显示用户资料
            let roleText = '';
            switch (user.role) {
                case 0:
                    roleText = '普通用户';
                    break;
                case 1:
                    roleText = '公司负责人';
                    break;
                case 2:
                    roleText = '系统管理员';
                    break;
                default:
                    roleText = '未知';
            }
            
            // 检查数据类型，确保正确比较
            const userStatus = typeof user.status === 'number' ? user.status : parseInt(user.status);
            const statusText = userStatus === 1 ? '正常' : '禁用';
            
            // 准备显示的公司信息
            let companyStatus = '';
            if (user.companyId) {
                companyStatus = `
                    <p><strong>所属公司ID：</strong>${user.companyId || ''}</p>
                    <p><strong>员工编号：</strong>${user.employeeNumber || '未设置'}</p>
                `;
                // 显示退出公司按钮
                if (leaveCompanyBtn) {
                    leaveCompanyBtn.style.display = 'inline-block';
                }
            } else {
                companyStatus = `<p><strong>公司状态：</strong>未加入公司</p>`;
                // 隐藏退出公司按钮
                if (leaveCompanyBtn) {
                    leaveCompanyBtn.style.display = 'none';
                }
            }
            
            userProfileElem.innerHTML = `
                <div class="user-profile-info">
                    <p><strong>ID：</strong>${user.id || ''}</p>
                    <p><strong>姓名：</strong>${user.name || ''}</p>
                    <p><strong>性别：</strong>${user.gender || ''}</p>
                    <p><strong>年龄：</strong>${user.age || ''}</p>
                    <p><strong>手机号：</strong>${user.phone || ''}</p>
                    <p><strong>邮箱：</strong>${user.email || '未设置'}</p>
                    <p><strong>住址：</strong>${(user.address && user.address !== 'null') ? user.address : '未设置'}</p>
                    <p><strong>身份证号：</strong>${(user.idCard && user.idCard !== 'null') ? maskIdCard(user.idCard) : '未设置'}</p>
                    <p><strong>角色：</strong>${roleText}</p>
                    <p><strong>账号状态：</strong>${statusText}</p>
                    ${companyStatus}
                </div>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> 如果需要修改密码，请前往登录页面使用"忘记密码"功能。
                </div>
            `;
        } else {
            userProfileElem.innerHTML = `<div class="alert alert-danger">获取用户信息失败：${data.message}</div>`;
        }
    })
    .catch(error => {
        // console.error('获取用户信息出错:', error);
        userProfileElem.innerHTML = '<div class="alert alert-danger">系统错误，请稍后再试</div>';
    });
}

// 更新用户个人资料
function updateUserProfile() {
    const form = document.getElementById('update-profile-form');
    const formData = new FormData(form);
    const urlEncodedData = new URLSearchParams(formData).toString();
    
    fetch('updateUserProfile', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: urlEncodedData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('个人资料更新成功');
            
            // 更新显示
            document.getElementById('profile-form-container').style.display = 'none';
            document.getElementById('user-profile').style.display = 'block';
            document.getElementById('edit-profile-btn').style.display = 'inline-block';
            
            // 重新加载用户资料
            loadUserProfile();
            
            // 更新页面上的用户名显示
            if (data.user && data.user.name) {
                document.getElementById('user-name').textContent = data.user.name;
            }
        } else {
            alert(data.message || '更新失败，请稍后再试');
        }
    })
    .catch(error => {
        // console.error('更新用户信息出错:', error);
        alert('系统错误，请稍后再试');
    });
}

// 退出公司
function leaveCompany() {
    // 首先检查离职申请状态
    checkResignationStatus()
        .then(status => {
            if (status === 0) { // 未申请离职
                showResignationForm();
            } else if (status === 3) { // 已提交申请，待审核
                alert('您已提交离职申请，正在等待公司审核，请耐心等待');
            } else if (status === 4) { // 离职申请已批准
                executeLeaveCompany();
            } else {
                alert('您当前无法申请离职，请确保您已加入公司并且不是公司负责人');
            }
        })
        .catch(error => {
            // console.error('检查离职状态出错:', error);
            alert('系统错误，请稍后再试');
        });
}

// 检查离职申请状态
function checkResignationStatus() {
    return fetch('checkResignationStatus')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                return data.status; // 返回申请状态：0-未申请，3-待审核，4-已批准
            } else {
                throw new Error(data.message || '获取离职申请状态失败');
            }
        });
}

// 显示离职申请表单
function showResignationForm() {
    // 创建模态框
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    
    modal.innerHTML = `
        <div class="modal-content">
            <span class="close-modal">&times;</span>
            <h3>提交离职申请</h3>
            <form id="resignation-form">
                <div class="form-group">
                    <label for="resignation-reason">离职原因（必填）：</label>
                    <textarea id="resignation-reason" name="reason" class="form-control" required rows="4"></textarea>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">提交申请</button>
                    <button type="button" id="cancel-resignation-btn" class="btn btn-secondary">取消</button>
                </div>
            </form>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 关闭按钮事件
    const closeBtn = modal.querySelector('.close-modal');
    closeBtn.addEventListener('click', () => {
        document.body.removeChild(modal);
    });
    
    // 取消按钮事件
    const cancelBtn = modal.querySelector('#cancel-resignation-btn');
    cancelBtn.addEventListener('click', () => {
        document.body.removeChild(modal);
    });
    
    // 表单提交事件
    const form = modal.querySelector('#resignation-form');
    form.addEventListener('submit', (event) => {
        event.preventDefault();
        const reason = document.getElementById('resignation-reason').value;
        
        if (!reason.trim()) {
            alert('请填写离职原因');
            return;
        }
        
        submitResignation(reason, modal);
    });
}

// 提交离职申请
function submitResignation(reason, modal) {
    const formData = new URLSearchParams();
    formData.append('reason', reason);
    
    fetch('submitResignation', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message || '离职申请提交成功，请等待公司审核');
            document.body.removeChild(modal);
            
            // 重新检查加入公司状态，这会同时检查离职申请状态
            checkJoinCompanyStatus();
            
            // 重新加载用户资料
            loadUserProfile();
        } else {
            alert(data.message || '离职申请提交失败，请稍后再试');
        }
    })
    .catch(error => {
        // console.error('提交离职申请出错:', error);
        alert('系统错误，请稍后再试');
    });
}

// 执行退出公司操作（离职申请已批准）
function executeLeaveCompany() {
    const formData = new URLSearchParams();
    formData.append('action', 'leave_company');
    
    fetch('userAccount', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message || '您已成功退出公司');
            
            // 重新加载用户资料
            loadUserProfile();
            
            // 检查加入公司状态
            checkJoinCompanyStatus();
        } else {
            if (data.needResignation) {
                showResignationForm();
            } else {
                alert(data.message || '退出公司失败，请稍后再试');
            }
        }
    })
    .catch(error => {
        // console.error('退出公司出错:', error);
        alert('系统错误，请稍后再试');
    });
}

// 注销账号
function deleteAccount() {
    const formData = new URLSearchParams();
    formData.append('action', 'delete_account');
    
    fetch('userAccount', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message || '您的账号已成功注销');
            
            // 如果返回了重定向地址，则进行重定向
            if (data.redirect) {
                window.location.href = data.redirect;
            }
        } else {
            alert(data.message || '注销账号失败，请稍后再试');
        }
    })
    .catch(error => {
        // console.error('注销账号出错:', error);
        alert('系统错误，请稍后再试');
    });
}

// 身份证号脱敏处理，将中间10位替换为*号
function maskIdCard(idCard) {
    if (!idCard || idCard.length < 15) return idCard;
    
    // 对于18位身份证
    if (idCard.length === 18) {
        return idCard.substring(0, 4) + '**********' + idCard.substring(14);
    }
    
    // 对于15位身份证
    if (idCard.length === 15) {
        return idCard.substring(0, 3) + '*********' + idCard.substring(12);
    }
    
    // 其他情况，只显示前4位和后4位
    return idCard.substring(0, 4) + '*'.repeat(idCard.length - 8) + idCard.substring(idCard.length - 4);
}